package com.yang.flower.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.flower.common.Result;
import com.yang.flower.entity.Cart;
import com.yang.flower.entity.User;
import com.yang.flower.mapper.CartMapper;
import com.yang.flower.service.CartService;
import com.yang.flower.utils.TokenUtils;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.ChartsheetDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Description: TODO
 * @Author: Yang
 * @DateTime: 2023/1/15 16:28
 **/
@RestController
@CrossOrigin
@RequestMapping("cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Resource
    private CartMapper cartMapper;

    @PostMapping
    public Result save(@RequestBody Cart cart){
        Long userId = TokenUtils.getCurrentUser().getId();
        Integer flowerId = cart.getFlowerId();
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).
                eq("flower_id",flowerId);
        Cart db = cartService.getOne(queryWrapper);
        if (db != null){
            db.setNum(db.getNum() + cart.getNum());
            cartService.saveOrUpdate(db);
            return Result.success();
        }
        if(cart.getId() == null){
            cart.setCreateTime(DateUtil.now());
            cart.setUserId(userId);
        }
        cartService.saveOrUpdate(cart);
        return Result.success();
    }

    @PostMapping("/changeNum")
    public Result changeNum(@RequestBody Cart cart){

        if(cart.getId() == null){
            cart.setCreateTime(DateUtil.now());
            cart.setUserId(TokenUtils.getCurrentUser().getId());
        }
        cartService.saveOrUpdate(cart);
        return Result.success();
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){
        Page<Cart> pageInfo = new Page<>(pageNum, pageSize);
        User currentUser = TokenUtils.getCurrentUser();
        Long userId = currentUser.getId();
        String role = currentUser.getRole();

        return Result.success(cartMapper.page(pageInfo,userId,role,name));
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        return Result.success(cartService.removeById(id));
    }

}
